#include "Box.h"

namespace lib3dw
{
	Box::Box()
	{
		translation = Vector3(0.0, 0.0, 0.0);
		scale = Vector3(1.0, 1.0, 1.0);
		UpdateParameters();
	}
	
	Box::~Box()
	{
		/*delete translation;
		delete scale;*/
		
	}
	
	void Box::SetTranslation(float x, float y, float z)
	{
		translation.x = x;
		translation.y = y;
		translation.z = z;
		UpdateParameters();
	}

	void Box::SetScale(float x, float y, float z)
	{
		scale.x = x;
		scale.y = y;
		scale.z = z;
		UpdateParameters();
	}
	
	void Box::UpdateParameters()
	{
		parameters[0].x = translation.x - scale.x / 2;
		parameters[0].y = translation.y - scale.y / 2;
		parameters[0].z = translation.z - scale.z / 2;
		
		parameters[1].x = translation.x + scale.x / 2;
		parameters[1].y = translation.y + scale.y / 2;
		parameters[1].z = translation.z + scale.z / 2;
	}

	bool Box::Intersect(PickRay* r, float t0, float t1) const 
	{
		float tmin, tmax, tymin, tymax, tzmin, tzmax;

		tmin = (parameters[r->GetSign0()].x - r->GetOrigin().x) * r->GetInverseDirection().x;
		tmax = (parameters[1-r->GetSign0()].x - r->GetOrigin().x) * r->GetInverseDirection().x;
		tymin = (parameters[r->GetSign1()].y - r->GetOrigin().y) * r->GetInverseDirection().y;
		tymax = (parameters[1-r->GetSign1()].y - r->GetOrigin().y) * r->GetInverseDirection().y;
		if ((tmin > tymax) || (tymin > tmax))
		return false;
		if (tymin > tmin)
		tmin = tymin;
		if (tymax < tmax)
		tmax = tymax;
		tzmin = (parameters[r->GetSign2()].z - r->GetOrigin().z) * r->GetInverseDirection().z;
		tzmax = (parameters[1-r->GetSign2()].z - r->GetOrigin().z) * r->GetInverseDirection().z;
		if ((tmin > tzmax) || (tzmin > tmax))
		return false;
		if (tzmin > tmin)
		tmin = tzmin;
		if (tzmax < tmax)
		tmax = tzmax;
		return ((tmin < t1) && (tmax > t0));
	}
	
	void Box::Draw()
	{
		glPushMatrix();
		glTranslated(parameters[0].x, parameters[0].y, parameters[0].z);
		glutSolidCube(0.3);
		glPopMatrix();
		
		glPushMatrix();
		glTranslated(parameters[1].x, parameters[1].y, parameters[1].z);
		glutSolidCube(0.3);
		glPopMatrix();
	}
}
